<template>
  <van-popup v-model:show="state.isShow" class="popup-box" style="height: 100%" position="right">
    <div class="edit-info-page page">
      <global-header background="white" title="修改头像" @back="state.isShow = false">
        <template #right>
          <div class="mr-[10px]">
            <div
              class="text-[13px] bg-[#3976CC] text-[#fff] w-[45px] h-[27px] rounded-sm flex justify-center items-center"
              @click="submit"
            >
              完成
            </div>
          </div>
        </template>
      </global-header>
      <div class="page-main flex justify-center items-center">
        <div
          v-if="!state.showCropper"
          class="relative h-[360px] flex flex-col items-center justify-center"
        >
          <img class="w-[300px] h-[300px] rounded-[300px] bg-gray-500" :src="netAvatar(avatar)" />
          <div class="text-[#6c6c6c] text-[15px] mt-[10px]">点击更换头像</div>
          <input
            type="file"
            ref="inputRef"
            class="opacity-0 w-[300px] h-[360px] absolute top-0 left-0"
            @change="afterRead"
          />
        </div>
        <Cropper
          ref="cropperRef"
          :img="state.img"
          :img-name="state.imgName"
          v-if="state.showCropper"
        />
      </div>
    </div>
  </van-popup>
</template>
<script setup lang="ts">
import { toast } from "@/utils/toast";
import { debounce } from "lodash-es";
import { useRoomStore } from "@/store/modules/room";
import { storeToRefs } from "pinia";
import { fileToBlob, netAvatar } from "@/utils/common";
import { reqUploadImg } from "@/api/user";
import { reqBasisConfigEdit } from "@/api/setting";
import { usePremsStore } from "@/store/modules/prems";

const emit = defineEmits(["update"]);

const roomStore = useRoomStore();
const premsStore = usePremsStore();
const { roomInfo } = storeToRefs(roomStore);
const state = reactive({
  isShow: false,
  updating: false,
  showCropper: false,
  img: roomInfo.value?.SysImg || "",
  imgName: ""
});

const inputRef = ref<HTMLInputElement | null>(null);
const cropperRef = ref<any>(null);
const avatar = ref(roomInfo.value?.SysImg || "");

const afterRead = async (ev: any) => {
  const file = ev.target.files[0];
  // 限制图片大小, 不能大于200kb
  if (file.size > 500 * 1024) {
    toast.fail("图片大小不能超过500kb");
    return;
  }
  fileToBlob(file).then((blob: any) => {
    state.showCropper = true;
    state.img = window.URL.createObjectURL(blob);
    state.imgName = file.name;
  });
};
let load: any = null;

const submit = debounce(
  async () => {
    if (!premsStore.isEditBasisSetting) {
      return toast.fail("暂无权限");
    }
    try {
      load = toast.loading("正在修改中");
      if (!cropperRef.value) {
        if (avatar.value == roomInfo.value?.SysImg) {
          load?.close();
          state.isShow = false;
          return;
        }
      } else {
        cropperRef.value.getAvatar().then(async (file: any) => {
          console.log(file.size);
          try {
            let param = new FormData();
            param.append("ImgPath", file);
            let res = await reqUploadImg(param);
            avatar.value = "/" + res.data.ImgPath;
            nextTick(async () => {
              await setAvatar();
            });
          } catch (error) {
            load?.close();
            console.log(error);
          }
        });
      }
    } catch (error) {
      load?.close();
    }
  },
  500,
  { leading: true, trailing: false }
);

const setAvatar = async () => {
  await reqBasisConfigEdit({
    SysImg: avatar.value
  });
  load?.close();
  toast.info("头像已修改");
  roomStore.actionRoomInfo();
  state.isShow = false;
};

const open = () => {
  state.isShow = true;
  state.showCropper = false;
  nextTick(() => {
    state.img = roomInfo.value?.SysImg || "";
    avatar.value = roomInfo.value?.SysImg || "";
  });
};

watch(
  () => roomInfo.value,
  val => {
    if (roomInfo.value?.SysImg) {
      state.img = val?.SysImg || "";
    }
  }
);

defineExpose({
  open
});
</script>
